package org.hbhk.hxl.gateway.route;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties.Web.Server;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 
 * 节点负载管理
 *
 */
@Component
public class MsNodeBalanceRule {

	private static Map<String, AtomicInteger> roundRobinMap = Maps.newHashMap();

	public static Server lbRoundRobin(List<Server> servers, String serviceId) {
		int size = servers.size();
		AtomicInteger roundRobin = roundRobinMap.get(serviceId);
		if (roundRobin == null) {
			roundRobin = new AtomicInteger(0);
			roundRobinMap.put(serviceId, roundRobin);
		}
		int index = (roundRobin.getAndAdd(1) + size) % size;
		return servers.get(index);
	}

	public static String roundRobin(List<String> servers, String serviceId) {
		int size = servers.size();
		AtomicInteger roundRobin = roundRobinMap.get(serviceId);
		if (roundRobin == null) {
			roundRobin = new AtomicInteger(0);
			roundRobinMap.put(serviceId, roundRobin);
		}
		int index = (roundRobin.getAndAdd(1) + size) % size;
		return servers.get(index);
	}

	public static void main(String[] args) {

		List<String> servers = Lists.newArrayList();

		for (int i = 0; i < 10; i++) {
			servers.add("" + i);

		}

		String serviceId = "hbhk";

		for (int i = 0; i < 10; i++) {
			Thread thread = new Thread(new Runnable() {

				@Override
				public void run() {

					for (int i = 0; i < 1000; i++) {
						System.out.println(roundRobin(servers, serviceId));
						try {
							TimeUnit.SECONDS.sleep(1);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});

			thread.start();
		}

	}

}